package com.fingard.dsp.bank.directbank.mipay01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

public class MIPAY01SinglePay extends MIPAY01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
            if (actItem == null) {
                retDetail.respCode = "0";
                retDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息";
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(retDetail);
                return retAts;
            }
            Map<String, Object> params = new HashMap<String, Object>();
            //接口名称
            params.put("service", "transfer");
            //接口版本
            params.put("serviceVersion", "1.0");
            //合作方商户ID
            params.put("partnerId", actItem.merchantId);
            //出款方商户id
            params.put("fromPartnerId", actItem.merchantId);
            //商户账户类型 2 普通商户账户 3营销活动账户 4红包账户
            params.put("accountType", "2");
            //字符集，目前只支持UTF-8
            params.put("inputCharset", "UTF-8");
            //服务器异步通知地址
            params.put("notifyUrl", actItem.notifyURL);
            //转账单号，32位数字
            params.put("outTransferId", p_req1908.singleDetail.askNumber);
            //收款方ID，这时必须是商户号
            params.put("benefitId", p_req1908.singleDetail.recAct);
            //转账类型，转账到商户，转账到商户id :1  转账到小米id账户: 2  转账到中间账户: 3
            params.put("transferType", "2");
            if ("1".equals(params.get("transferType"))) {
                //受益商户，转账到商户必填
                params.put("benefitAccountType", "2");
            } else if ("2".equals(params.get("transferType"))) {
                //用户实名认证 是否要求用户实名认证true 要求 false 不要求
                params.put("needUserVerify", "true");
            }
            //转账金额，使用现金公钥进行加密
            PublicKey key = getPublicKey(actItem.oppCertFilePath);
            params.put("transferAmount", encrypt(key, StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount)));
            //转账描述
            params.put("transferDesc", p_req1908.singleDetail.description);
            //转账请求时间
            params.put("requestTime", Format.DateTimeFormat.format(p_req1908.singleDetail.getPayDateTime()));
            //转账请求IP地址
            params.put("requestIp", bankFront.serverIP);
            //扩展字段
            JSONObject info = new JSONObject();
            info.put("extraInfo",p_req1908.singleDetail.memo);
            params.put("extraInfo", info.toJSONString());

            String content = convertMapToStr(params);
            String sign = getSign(content, actItem);
            //签名方式
            params.put("signType", "RSA");
            //签名
            params.put("sign", sign);

            WriteBankLogStep2(convertMapToStr(params));
            String[] tmpStrRet = sendToBank(params, bankFront.getUrl("singlePay"));
            WriteBankLogStep3(tmpStrRet[1]);

            if (tmpStrRet[0].length() == 0) {
                StringBuilder sbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], sbMsg);
                if (tmpBkReader != null) {
                    String isSuccess = tmpBkReader.getFirstText("/cashpayTransfer/baseInfo/isSuccess");
                    String responseCode = tmpBkReader.getFirstText("/cashpayTransfer/baseInfo/responseCode");
                    retDetail.respCode = "0";
                    retDetail.respInfo = responseCode;
                    retDetail.transState = isSuccess + "+" + responseCode;
                    retDetail.payInfoCode = responseCode;
                    retDetail.outTransID = tmpBkReader.getFirstText("/cashpayTransfer/transferInfo/transferId");
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = sbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retDetail.respCode = "-1";
            retDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        retDetail.reqSeqID = p_req1944.askNumber;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "");
            if (actItem == null) {
                retDetail.respCode = "0";
                retDetail.respInfo = "未找到账号[" + p_req1944.payAct + "]商户配置信息";
                retDetail.reqSeqID = p_req1944.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(retDetail);
                return retAts;
            }
            Map<String, Object> params = new HashMap<String, Object>();
            //接口名称
            params.put("service", "TRANSFERQUERY");
            //接口版本
            params.put("serviceVersion", "1.0");
            //合作方商户ID
            params.put("partnerId", actItem.merchantId);
            //出款方商户id
            params.put("fromPartnerId", actItem.merchantId);
            //字符集，目前只支持UTF-8
            params.put("inputCharset", "UTF-8");
            //转账单号，32位数字
            params.put("outTransferId", p_req1944.askNumber);
            //转账请求时间
            params.put("requestTime", Format.DateTimeFormat.format(p_req1944.getBgnDateTime()));

            String content = convertMapToStr(params);
            String sign = getSign(content, actItem);
            //签名方式
            params.put("signType", "RSA");
            //签名
            params.put("sign", sign);
            WriteBankLogStep2(convertMapToStr(params));
            String[] tmpStrRet = sendToBank(params, bankFront.getUrl("querySglPay"));
            WriteBankLogStep3(tmpStrRet[1]);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder sbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], sbMsg);
                if (tmpBkReader != null) {
                    String isSuccess = tmpBkReader.getFirstText("/cashpayQuery/baseInfo/isSuccess");
                    String responseCode = tmpBkReader.getFirstText("/cashpayQuery/baseInfo/responseCode");
                    if (StringHelper.hasAnyChar(isSuccess)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = responseCode;
                        retDetail.transState = isSuccess + "+" + responseCode;
                        retDetail.payInfoCode = responseCode;
                        retDetail.outTransID = tmpBkReader.getFirstText("/cashpayQuery/transferInfo/transferId");
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = sbMsg.toString();
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = sbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retDetail.respCode = "-1";
            retDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
